#include <stdio.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h> /* superset of previous */
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "cJSON.h"
#define N 4096

char str[4096];

void *heartbeat(void *arg)
{
    //心跳协议发送
    while (1)
    {
        char *str;
        cJSON *cjson_test = cJSON_CreateObject();
        cJSON_AddNumberToObject(cjson_test, "type", 3);
        str = cJSON_Print(cjson_test);
        int sockfd = (int)arg;
        send(sockfd, str, sizeof(str), 0);
        sleep(60);
    }
}
int main(int argc, char const *argv[])
{
    //创建socket
    int broadfd;

    //创建一个socket文件描述符
    broadfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (broadfd < 0)
    {
        perror("sock err");
        return -1;
    }

//打开广播设置，允许发送广播包
#if 1
    int on = 1;
    if (setsockopt(broadfd, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on)) < 0)
    {
        perror("set err");
        return -1;
    }
#endif

    ssize_t len;
    char buf[N] = {0};
    struct sockaddr_in broad_addr;

    broad_addr.sin_family = AF_INET;
    broad_addr.sin_port = htons(8888);                 //端口号
    broad_addr.sin_addr.s_addr = inet_addr("0.0.0.0"); //IP

    int addrlen = sizeof(broad_addr);

    //发送"coffee"代表公司名
    int ret = sendto(broadfd, "coffee", 7, 0, (struct sockaddr *)&broad_addr, addrlen);
    if (ret < 0)
    {
        perror("send to err");
        return -1;
    }

    //如果对方回复"yes"，那么接收对方的地址
    struct sockaddr_in dev_addr;
    recvfrom(broadfd, buf, N, 0, (struct sockaddr *)&dev_addr, &addrlen);
    if (strcmp(buf, "yes") != 0)
    {
        printf("not my company device\n");
        return -1;
    }

    //建立TCP连接
    int tcpfd = socket(AF_INET, SOCK_STREAM, 0);
    if (tcpfd < 0)
    {
        perror("sock err");
        return -1;
    }

    if (connect(tcpfd, (struct sockaddr *)&dev_addr, addrlen) < 0)
    {
        perror("connect err");
        return -1;
    }


        //char buf[4096] = "";
    bzero(buf, 4096);
    FILE *fd = NULL;
    if ((fd = fopen("/mnt/config/dev_config.json", "rw")) == NULL)
    {
        perror("fopen error");
    }
    else if (fread(buf, 4096, 1, fd) != 0)
    {
        printf("fread error\n");
    }

    printf("connect success\n");
    sprintf(str,"{\"type\": 2,\"data\": {\"flag\": \"start\",\"file_name\": \"/mnt/config/node2.json\",\"file_len\": %d}}",strlen(buf));
    //strcpy(str, "{\"type\": 1}");
    send(tcpfd, &str, strlen(str), 0);
    recv(tcpfd, &str, sizeof(str), 0);
    printf("%s\n",buf);
    //发送文本
    send(tcpfd, buf, strlen(buf), 0);

    sleep(1);
    send(tcpfd, &str, strlen(str), 0);


    close(broadfd);
    close(tcpfd);
    return 0;
}
